<?php

namespace app\common\service;

class TencentTopUpService
{
    const MERCH_ID = 10033;
    const API_KEY = '8xhv46ckh9rah0j';
    const SERVER_API_URL = 'http://www.qb141319.com/Api/';
    const CALLBACK_URL = 'http://www.qb141319.com/Api/';
    // 充值成功
    const SUCCESS = 101;
    // 充值中
    const UNDERWAY = 102;
    // 可疑订单
    const DUBIOUS = 103;
    protected static $errorCode = '';

    // 获取当前账号余额信息
    public static function getBalance()
    {
        $url = 'QueryMerchant';
        $param = [
            'MerchantID'=>self::MERCH_ID
        ];
        $param['Sign'] = self::makeSign($param);
        $result = self::curlPost($url, $param);
        if (isset($result['balance'])){
            return sprintf('%.2f', floatval($result['balance']));
        }
        return 0;
    }

    // Q币充值
    public static function qbPay($order_code, $number, $account)
    {
        $url = 'Pay';
        $param = [
            'MerchantID'=>self::MERCH_ID,
            'MerchantOrderID'=>$order_code,
            'ProductID'=>10015,
            'BuyAmount'=>$number,
            'TargetAccount'=>$account,
            //'ResponseUrl'=>self::CALLBACK_URL
        ];
        $param['Sign'] = self::makeSign($param);
        $result = self::curlPost($url, $param);
        if (!empty($result['state'])){
            self::$errorCode = $result['state'];
            if ($result['state'] == self::SUCCESS){
                return true;
            }
            if ($result['state'] == self::UNDERWAY || $result['state'] == self::DUBIOUS){
                return true;
                // 通管异步订单处理
                // return self::queryOrder($order_code);
            }
        }
        return false;
    }

    /**
     * 订单查询
     * @param $order_code
     * @param $qrn
     * @return bool
     */
    public static function queryOrder($order_code, $qrn = 0)
    {
        if ($qrn >= 5){
            return false;
        }
        $url = 'QueryOrder';
        $param = [
            'MerchantID'=>self::MERCH_ID,
            'MerchantOrderID'=>$order_code
        ];
        $param['Sign'] = self::makeSign($param);
        $result = self::curlPost($url, $param);
        if (!empty($result['state'])){
            self::$errorCode = $result['state'];
            if ($result['state'] == self::SUCCESS){
                return true;
            }
            if ($result['state'] == self::UNDERWAY || $result['state'] == self::DUBIOUS){
                usleep(100);
                return self::queryOrder($order_code);
            }else{
                return false;
            }
        }
        return false;
    }

    // 错误状态码
    public static function getError()
    {
        if (empty(self::$errorCode)){
            return '未知错误';
        }
        $state_array = [
            '101'=>'交易成功',
            '102'=>'充值中',
            '103'=>'可疑订单',
            '201'=>'参数不合法',
            '202'=>'签名错误',
            '203'=>'充值帐号不存在',
            '301'=>'商家不存在',
            '302'=>'商家已被禁用',
            '304'=>'IP地址不合法',
            '305'=>'账户余额不足',
            '306'=>'订单号重复',
            '307'=>'订单不存在',
            '401'=>'商品不存在',
            '405'=>'购买数量不合法',
            '501'=>'取消订单',
            '601'=>'渠道问题（详见状态描述）',
            '901'=>'未知原因（详见状态描述）',
        ];
        return $state_array[self::$errorCode];
    }

    protected static function makeSign($param)
    {
        $str = implode('', array_values($param)) . self::API_KEY;;
        return md5($str);
    }

    /**
     * 发起 server 请求
     * @param $action
     * @param string $token
     * @return array|mixed
     */
    protected static function curlGet($action)
    {
        $action = self::SERVER_API_URL.$action;
        $headers = [];
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $action);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $output = curl_exec($curl);
        curl_close($curl);
        return json_decode($output, true);
    }

    /**
     * 发起cmd命令请求
     * @param $action
     * @param $params
     * @return mixed
     */
    protected static function curlPost($action, $params, $contentType='json', $httpMethod='POST')
    {
        $action = self::SERVER_API_URL.$action;
        $httpHeader[] = 'Accept:*/*';
        $ch = curl_init();
        if ($httpMethod=='POST' && $contentType=='urlencoded') {
            $httpHeader[] = 'Content-Type:application/x-www-form-urlencoded';
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
        }
        if ($httpMethod=='POST' && $contentType=='json') {
            $httpHeader[] = 'Content-Type:Application/json';
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params) );
        }
        if ($httpMethod=='GET' && $contentType=='urlencoded') {
            $action .= strpos($action, '?') === false?'?':'&';
            $action .= http_build_query($params);
        }
        curl_setopt($ch, CURLOPT_URL, $action);
        curl_setopt($ch, CURLOPT_POST, $httpMethod=='POST');
        curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false); //处理http证书问题
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACHE, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $ret = curl_exec($ch);
        if (false === $ret) {
            $ret =  curl_errno($ch);
        }
        curl_close($ch);

        return self::fromXml($ret);
    }

    /**
     * 将xml转为array
     * @param $xml
     * @return mixed|void
     */
    protected static function fromXml($xml)
    {
        if(!$xml){
            return false;
        }
        $xml = simplexml_load_string($xml);
        $json = json_encode($xml);
        return json_decode($json,TRUE);
    }
}